package cn.ecnu.interceptor;


import cn.ecnu.common.constant.Constant;
import cn.ecnu.common.exception.RRXException;
import cn.ecnu.common.utils.JwtToken;
import cn.ecnu.common.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) return true;
        HandlerMethod handlerMethod = (HandlerMethod) handler; // 处理这个请求的函数
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(JwtToken.class)) { // 获取方法上的注解
            JwtToken jwtToken = method.getAnnotation(JwtToken.class);
            if (jwtToken != null && jwtToken.required()) {
                if (token == null) {
                    throw new RRXException(Constant.AUTH_ERROR.getMsg(), Constant.AUTH_ERROR.getCode());
                }
                Integer userId = jwtUtil.getUserId(token);
                request.setAttribute("userId", userId);
                response.setHeader("token", jwtUtil.sign(userId));
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
